<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-table :data="tableData" border stripe>
      <!-- 展开列 -->
      <el-table-column width="60" type="expand">
        <!--  -->
        <template slot-scope="scope">
          <!-- 行 -->
          <el-row
            :class="['bottomline']"
            v-for="item1 in scope.row.children"
            :key="item1.id"
          >
            <!-- 一级导航 -->
            <el-col :span="5" style="display: flex">
              <el-tag closable @close="deltag(scope.row, item1.id)">{{
                item1.authName
              }}</el-tag>

              <i class="el-icon-caret-right"></i
            ></el-col>
            <el-col :span="19">
              <el-row v-for="item2 in item1.children" :key="item2.id">
                <el-col :span="6"
                  ><el-tag
                    type="success"
                    closable
                    @close="deltag(scope.row, item2.id)"
                    >{{ item2.authName }}
                    <!-- 二级导航 -->
                    <i class="el-icon-caret-right"></i></el-tag
                  ><i class="el-icon-caret-right"></i
                ></el-col>

                <el-col :span="18">
                  <!-- 三级导航 -->
                  <el-tag
                    :class="['tag']"
                    type="warning"
                    closable
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    @close="deltag(scope.row, item3.id)"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="#" width="60" type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"> </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <div class="btns">
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="openDialog('edit', scope.row.id)"
            ></el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="openDialog('del', scope.row.id)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="权限分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                icon="el-icon-s-tools"
                size="mini"
                type="warning"
                @click="showDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 树形控件 -->
      <!--  node-key="id" 表示控件的唯一值   purviewList：表示所有的 authName-->
      <!-- show-checkbox：显示复选框   :default-checked-keys：默认被选中的唯一属性值（ID）-->
      <!-- :props="defaultProps" ：嵌套值，显示的值 -->
      <el-tree
        ref="treeLef"
        :default-checked-keys="defKeys"
        node-key="id"
        show-checkbox
        default-expand-all
        :data="purviewList"
        :props="defaultProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>



<script>
import { userListAPI, delqxAPI, purviewListAPI, purviewpointAPI } from '@/api/user.js'
export default {
  data () {
    return {
      roleId: null,
      dialogVisible: false,
      tableData: [],
      purviewList: [],
      defaultProps: {
        // 通过children字段进行嵌套
        children: 'children',
        // label:需要显示的字段
        label: 'authName'
      },
      //默认被选择的值的id
      defKeys: []
    }
  },
  created () {
    this.initData()
  },
  methods: {
    //确认按钮
    async allRights (id) {
      const keys = [

        //先获取到tree元素，tree身上有getCheckedKeys/getHalfCheckedKeys这个方法，它的返回值是一个数组，表示所有被选择的节点的ID
        ...this.$refs.treeLef.getCheckedKeys(), ...this.$refs.treeLef.getHalfCheckedKeys()
      ]
      console.log(keys, 'keys');
      const idstr = keys.join(',')
      const res = await purviewpointAPI(this.roleId, idstr)
      console.log(res, '778899');
      this.initData()
      this.dialogVisible = false

    },
    //通过递归找到数组中最底层的被选择的ID
    getLeafKeys (node, arr) {
      if (!node.children) {
        //说明找到最底层
        console.log(arr, 'arr');
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },



    //展开对话框
    async showDialog (role) {
      this.dialogVisible = true
      this.roleId = role.id
      const res = await purviewListAPI()
      this.purviewList = res.data
      // console.log(this.$refs.treeLef.getCheckedKeys(true), 'getCheckedKeys');
      this.getLeafKeys(role, this.defKeys)
      // console.log(res, 'purviewListAPI');
    },
    //对话框
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(() => {
          //需要在关闭对话框的时候，清空数组，否则数组的值会叠加
          this.defKeys = []
          done();
        })
        .catch(_ => { });
    },
    //删除标签
    async deltag (role, delid) {
      const res = await this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (res == 'confirm') {
        const res = await delqxAPI(Number(role.id), delid)
        // console.log(res, 'resid');
        //发送请求后，表格会收起，此时不能直接渲染，而是直接复值。
        role.children = res.data
        this.$message.success('删除成功！')
      } else {
        this.$message.info('取消删除！')
      }
    },
    //渲染
    async initData () {
      const res = await userListAPI()
      this.tableData = res.data
      console.log(res, 'userListAPI');
    }
  }
}
</script>

<style lang='less'  scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.bottomline {
  margin: 12px 30px;
  border-bottom: 1px solid #eceef4;

  .el-tag {
    margin-bottom: 12px;
    margin-left: 8px;
  }
}
</style>